<?php
declare (strict_types = 1);

namespace App\Models;

//use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 管理员表
 */
class AdminModel extends BaseModel
{
    use SoftDeletes;
    protected $table = 'admin';

    protected $fillable = ['real_name','account','password','roles_id','create_time','update_time'];

    /**
     * 关联角色表
     */
    public function admin_roles() {
        return $this->hasOne(AdminRolesModel::class,'id','roles_id');
    }

    /**
     * 获取所属权限组
     * @param [type] $admin_id 管理登陆id
     */
    public static function getRoles($admin_id)
    {
        $res = self::select(['id','roles_id'])
            ->with(['admin_roles'=>function($query){
                return $query->select(['id','rules']);
            }])
            ->whereHas('admin_roles', function($query){
                return $query->where('status',1);
            })
            ->where('unique',$admin_id)
            ->first();

        if($res->admin_roles->rules != 'all') {
            return $res->id;
        }
        return "";
    }

    /**
     * 获取管理员列表
     */
    public static function getList($pageSize, $page, $map)
    {
        $res = self::select('*')
            ->with(['admin_roles'=>function($query){
                return $query->select(['title','id']);
            }])
//            ->whereHas('admin_roles', function($query){
//                return $query->where('status',1);
//            })
            ->where($map)
            ->orderBy('last_time','desc')
            ->orderBy('create_time','desc')
            ->paginate($pageSize,[],'page', $page)->toArray();

        return $res;
    }

    /**
     * 获取权限
     */
    public static function getJurisdiction($admin_id)
    {
        $roles = self::select(['roles_id','unique'])
            ->with(['admin_roles'=>function($query){
                return $query->select(['id','title','rules']);
            }])
            ->whereHas('admin_roles',function($query){
                return $query->where('status',1);
            })
            ->where("unique", $admin_id)
            ->first();

        if($roles){
            $roles = $roles->toArray();
            $roles['title'] = $roles['admin_roles']['title'];
            $roles['rules'] = $roles['admin_roles']['rules'];
        }

        return $roles;
    }
}
